package com.aabbc.zk.schedule;

import com.aabbc.zk.listener.ZookeeperConnectionStateListener;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.curator.x.discovery.ServiceDiscovery;
import org.apache.curator.x.discovery.ServiceDiscoveryBuilder;
import org.apache.curator.x.discovery.ServiceInstance;
import org.apache.zookeeper.CreateMode;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.concurrent.TimeUnit;

/**
 * ZookeeperLeaderSchedule
 *
 * @author: chenfenghai
 * @version: 1.0
 * @date: 2019-12-18 16:05
 * @blame Team
 */
@Slf4j
@Component
public class ZookeeperLeaderSchedule {


    private static final String path = "/root/leaderlatch";

    private static final String connectStr = "127.0.0.1:2181";

    private static CuratorFramework curatorFramework;
    private static LeaderLatch leaderLatch;

    static  {
        curatorFramework = CuratorFrameworkFactory
                .builder()
                .connectString(connectStr)
                .retryPolicy(new ExponentialBackoffRetry(3000, 30))
                .connectionTimeoutMs(5000)
                .sessionTimeoutMs(5000)
                .build();

        curatorFramework.start();

        try {
            ServiceInstance<String> instance = ServiceInstance.<String>builder().payload("thing").name("test").port(10064).build();
            ServiceDiscovery<String> discovery = ServiceDiscoveryBuilder.builder(String.class).basePath("/test").client(curatorFramework).thisInstance(instance).build();
            discovery.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Lazy
    @Scheduled(cron = "0/10 * * * * ?")
    void testZookeeperLeaderPrint() throws Exception {
        //log.info("size: {}",leaderLatch.getParticipants().size());
        //log.info("testZookeeperLeaderPrint..." + leaderLatch.hasLeadership());
    }
}
